using Abc.Core;
using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Mapster;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Fur.DynamicApiController;
using Microsoft.Extensions.Caching.Memory;
using Utils;
using Microsoft.AspNetCore.Authorization;
using Fur;
using Fur.Authorization;
using System;
using Newtonsoft.Json.Linq;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.AspNetCore.Http;

namespace Abc.Application
{
    [Injection(Proxy = typeof(LogDispatchProxy))]
    public class UserServices : IUserServices, ITransient
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IRepository<User> _userRepository;
        private readonly IMemoryCache _memoryCache;
        private readonly IAuthorizationManager _authorizationManager;
        public UserServices(IRepository<User> userRepository
            , IHttpContextAccessor httpContextAccessor
            , IAuthorizationManager authorizationManager)
        {
            _userRepository = userRepository;
            _memoryCache = App.GetService<IMemoryCache>(); ;
            _httpContextAccessor = httpContextAccessor;

            _authorizationManager = authorizationManager;
        }
        /// <summary>
        /// 新增一条
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultData<string>> Insert(UserDto input)
        {
            var resultdata = new ResultData<string>();
            // 如果不需要返回自增Id，使用 InsertAsync即可

            var dbentity = await _userRepository.DetachedEntities.FirstOrDefaultAsync(o => o.Account.ToLower() == input.Account.ToLower());

            if (dbentity != null)
            {
                resultdata.Msg = "账号已存在";
                return resultdata;
            }

            var newEntity = await _userRepository.InsertAsync(input.Adapt<User>());


            resultdata.State = true;
            resultdata.Msg = "成功";
            return resultdata;
        }

        /// <summary>
        /// 更新一条
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultData<string>> Update(UserDto input)
        {
            var resultdata = new ResultData<string>();
            var dbentity = await _userRepository.Entities.SingleAsync(u => u.Id == input.Id);
            input.Adapt(dbentity);
            await _userRepository.UpdateAsync(dbentity);



            resultdata.State = true;
            resultdata.Msg = "成功";
            return resultdata;
        }
        /// <summary>
        /// 新增或更新一条
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultData<string>> AddOrUpdate(UserDto input)
        {
            if (input.Id > 0)
            {
                return await Update(input);
            }
            else
            {
                return await Insert(input);
            }
        }

        /// <summary>
        /// 删除一条
        /// </summary>
        /// <param name="id"></param>
        public async Task<ResultData<string>> Delete(int id)
        {
            var resultdata = new ResultData<string>();

            var dbentity = await _userRepository.FindOrDefaultAsync(id);

            if (dbentity == null)
            {
                resultdata.Msg = "账号不存在";
                return resultdata;
            }
            if (dbentity.Account.ToLower() == "Administrator".ToLower())
            {
                resultdata.Msg = "系统账号不允许删除";
                return resultdata;
            }


            await _userRepository.FakeDeleteAsync(id);



            resultdata.State = true;
            resultdata.Msg = "成功";
            return resultdata;
        }

        /// <summary>
        /// 查询一条
        /// </summary>
        /// <param name="id"></param>
        public async Task<UserDto> Find(int id)
        {
            var dbentity = await _userRepository.FirstOrDefaultAsync(o => o.Id == id);
            return dbentity.Adapt<UserDto>();
        }



        /// <summary>
        /// 查询所有
        /// </summary>
        /// <returns></returns>
        public async Task<List<UserDto>> GetAll()
        {
            var queryable = _userRepository.AsQueryable();
            queryable = queryable.Where(o => o.UserType == UserType.普通用户);

            var entities = queryable.ProjectToType<UserDto>();
            return await entities.ToListAsync();
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="querydto"></param>
        /// <returns></returns>
        public async Task<Fur.DatabaseAccessor.PagedList<UserDto>> GetAllByPage(UserQueryDto querydto)
        {
            var queryable = _userRepository.Where(o => o.UserType == querydto.UserType);

            if (!string.IsNullOrWhiteSpace(querydto.KeyWords))
            {
                var kw = querydto.KeyWords.ToLower();
                queryable = queryable.Where(o => o.Account.Contains(kw)
                || o.Nick.Contains(kw)
                || o.Phone.Contains(kw)
                || o.Tel.Contains(kw));
            }


            var entities = queryable.ProjectToType<UserDto>();
            return entities.ToPagedList(querydto.Page, querydto.Limit);
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="querydto"></param>
        /// <returns></returns>
        public async Task<PagedListToLayui<UserDto>> GetAllByPageToLayui(UserQueryDto querydto)
        {
            var pageResult = _userRepository.Where(o => o.UserType == UserType.普通用户)
                .ProjectToType<UserDto>();
            return pageResult.ToPagedListToLayui(querydto.Page, querydto.Limit);
        }




    }

    public interface IUserServices
    {
        /// <summary>
        /// 新增一条
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        Task<ResultData<string>> Insert(UserDto input);
        /// <summary>
        /// 更新一条
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        Task<ResultData<string>> Update(UserDto input);

        /// <summary>
        /// 新增或更新一条
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        Task<ResultData<string>> AddOrUpdate(UserDto input);

        /// <summary>
        /// 删除一条
        /// </summary>
        /// <param name="id"></param>
        Task<ResultData<string>> Delete(int id);

        /// <summary>
        /// 查询一条
        /// </summary>
        /// <param name="id"></param>
        Task<UserDto> Find(int id);

        /// <summary>
        /// 查询所有
        /// </summary>
        /// <returns></returns>
        Task<List<UserDto>> GetAll();

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="querydto"></param>
        /// <returns></returns>
        Task<Fur.DatabaseAccessor.PagedList<UserDto>> GetAllByPage(UserQueryDto querydto);
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="querydto"></param>
        /// <returns></returns>
        Task<PagedListToLayui<UserDto>> GetAllByPageToLayui(UserQueryDto querydto);


    }


}
